import time
import json
import math


# 导入的json
jsonSrc='test.json'
# 指定格式的ass文件
styleSrc='style.ass'
# 输出ass
targetFile='out.ass'
timeList = []
dictList = []


# 指定一行字幕的文本
def getOneLine(objIndex,obj):
    oneLine=''
    # 开始时间
    startTime=timeList[objIndex+i]
    # 结束时间
    endTime=timeList[objIndex+i+1]
    # 移动坐标
    moveStartX='40'
    moveStartY=1080-(i)*72
    moveEndX='40'
    moveEndY=1080-(i+1)*72
    # 昵称样式
    speakerStyle =''
    # 说话内容样式
    contentStyle ='{\c&HFFFFFF&}'
    # 字符串
    oneLine += f'Dialogue: 0,{startTime},{endTime},all,,0,0,0,,'
    oneLine += '{'
    oneLine += f'\\move({moveStartX},{moveStartY},{moveEndX},{moveEndY},0,100)'
    oneLine += '}'
    oneLine += f'{speakerStyle}{obj["username"]} {contentStyle}{obj["text"]}\n'
    return oneLine


# 读取json
file = open(jsonSrc,mode='r',encoding='utf-8')
jsonDict=json.loads(file.read())
file.close()
# 整个文件的开始时间的时间戳
startTimeStamp=jsonDict["info"]["start_time"]
contentDict=jsonDict["full_comments"]
for one in contentDict:
    try:
        # 用这个过滤礼物
        one["text"]
        # 时间戳，json里的时间戳不能直接用所以要进行一些运算
        timeStamp=(one["time"]-startTimeStamp)/(10**3)+3600*16
        thisTime = time.localtime(timeStamp)
        # 转换好的时间单独整个列表
        timeList.append(time.strftime("%H:%M:%S",thisTime)+"."+str(math.modf(timeStamp)[0])[2:4])
        # 过滤出来的字幕单独整个列表
        dictList.append(one)
    except:
        print('有个礼物已经过滤了')


# 写入ass
file = open(targetFile,mode='w',encoding='utf-8')
file.write(open(styleSrc,mode='r',encoding='utf-8').read())
objIndex=0
for obj in dictList:
    assStr=''
    for i in range(0,15):
        if objIndex+i<len(timeList)-1:
            assStr+=getOneLine(objIndex,obj)
    file.write(assStr)
    objIndex+=1
file.close()
